package com.zlp.clazz;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class ClassLoaderDemo_3{

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        /*
        * 如果子类的构造方法中没有显示的调用基类构造方法，则系统默认调用基类无参数的构造方法注意：如果子类的构造方法中
        * 既没有显示的调用基类构造方法，而基类中又没有默认无参的构造方法，则编译出错，
        * this(checkCreateClassLoader(), getSystemClassLoader());
        * //给自定义的class加载器的父类加载器设置为系统类加载器
        * */
        MyClassLoader myClassLoader = new MyClassLoader();
        Class<?> mapSum = myClassLoader.loadClass("MapSum");
        Object o = mapSum.newInstance();
        Method get = mapSum.getMethod("get");
        System.out.println(get.invoke(o));
        System.out.println(mapSum.getClassLoader());
        System.out.println(mapSum.getClassLoader().getParent());
    }
}

/**
 * 自定义类加载器
 */
class MyClassLoader extends ClassLoader{

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String path = "D:\\classLoaderTest\\"+name+".class";

        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            Files.copy(Paths.get(path),bos);
            byte[] bytes = bos.toByteArray();
            return defineClass(name,bytes,0,bytes.length);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ClassNotFoundException("类文件未找到",e);
        }
    }
}
